<?php
/**
 * admin service file Created by PhpStorm.
 * User: wumengmeng
 * Date: 2020/02/25
 * Time: 15:21
 */

namespace Modules\Shop\Service;

use HiCommon\Repository\GoodsProductRepository;
use HiCommon\Repository\StoreOrderRefundRepository;
use HiCommon\Repository\StoreOrderRepository;
use HiCommon\Repository\StoreOrderGoodsRepository;
use HiCommon\Service\PayRefundService;
use HiCommon\Service\PayService;

class StoreOrderRefundService
{
    /**
     * 获取分页数据
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_list($arr_search)
    {
        try {
            $where['shop_id'] = $arr_search['shop_id'];//门店id
            if (!empty($arr_search['refund_no'])) {
                $where['refund_no'] = $arr_search['refund_no'];
            }
            if (!empty($arr_search['apply_state'])) {
                $where['apply_state'] = $arr_search['apply_state'];
            }

            $arr_option['where'] = $where;
            $arr_option['with'] = ['refund_reason_id'];

            $data = StoreOrderRefundRepository::get_list($arr_option);
            $data = list_page_data($data, $arr_search);

            return hello_success('成功', $data);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }


    /**
     * 查询一条数据
     *
     * @param int $n_id
     *
     * @return mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function get_one(int $n_id)
    {
        try {
            $n_id = (int)$n_id;
            if ($n_id <= 0) {
                hello_error('数据ID不能为空');
            }

            //查询
            $arr_option['with'] = ['get_order_refund_goods', 'refund_reason_id'];
            $res = StoreOrderRefundRepository::get_one($n_id, $arr_option)->toarray();
            if (empty($res)) {
                return hello_error('查询失败');
            }
            if (!empty($res['picture'])) {
                $picture = json_decode($res['picture']);
                foreach ($picture as $key => $value) {
                    $res['picture_array'][] = oss_full_url($value);
                }
            }
            foreach ($res['get_order_refund_goods'] as $item) {
                $res['order_goods'][] = $item['order_goods'];
            }

            return hello_success('查询成功', $res);
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    /***
     * 检查该订单的所有商品是否全部退单
     * @param int $order_id
     * @param int $status
     */
    public function check_goods_all_back(int $order_id, $status = 9)
    {
        $arr_option = ['with' => ['getOrderGoods2'], 'field' => ['id']];
        $res = StoreOrderRepository::get_one($order_id, $arr_option)->toarray();
        if (min(array_column($res['get_order_goods2'], 'is_refund')) == 1) {
            //商品全部退还更新主变订单状态为已退货已退款
            StoreOrderRepository::change_one_state($order_id, $status);
        }
    }

    /**
     * 售后操作
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function order_refund_handle($arr_input)
    {
        try {
            if ($arr_input['id'] <= 0) {
                return hello_error('数据id不能为空');
            }
            $refund_id = (int)$arr_input['id'];
            $type = (int)$arr_input['type'];
            if (empty($refund_id)) {
                return hello_error('退单id不能为空');
            }
            //查询
            $arr_option['with'] = ['get_refund_price', 'store_order'];
            $refund_ary = StoreOrderRefundRepository::get_one($refund_id, $arr_option)->toarray();

            if ($type == 1) {//同意申请

                $up_array = ['apply_state' => 2, 'deal_at' => date('Y-m-d H:i:s')];

                self::check_goods_all_back((int)$refund_ary['store_order_id']);

                //消息通知
                $dataNotice = [
                    'notice_type' => 'ptshp_sales_message_push',
                    'refund_order_id' => $refund_id,
                    'type' => 51,
                    'title' => '同意申请通知',
                    'content' => '售后申请商家已同意。'
                ];
                predis_notice_queue_in($dataNotice);

            } elseif ($type == 2) {//拒绝申请

                $up_array = ['apply_state' => 3, 'deal_at' => date('Y-m-d H:i:s')];

                foreach ($refund_ary['get_refund_price'] as $key => $value) {
                    StoreOrderGoodsRepository::edit_one(['id' => $value['get_order_goods']['id'], 'is_refund' => 0]);
                }

                //消息通知
                $dataNotice = [
                    'notice_type' => 'ptshp_sales_message_push',
                    'refund_order_id' => $refund_id,
                    'type' => 50,
                    'title' => '拒绝申请通知',
                    'content' => '售后申请已被商家拒绝。'
                ];
                predis_notice_queue_in($dataNotice);

            } elseif (!empty($refund_ary['get_refund_price']) && $type == 3) {//确认退款

                $s_order_sn = $refund_ary['store_order']['order_no'];//订单编号
                $s_refund_sn = $refund_ary['refund_no'];//退单编号

                self::check_goods_all_back((int)$refund_ary['store_order_id'], 7);

                //退款处理
                return PayRefundService::api_online_pay_refund($s_order_sn, $s_refund_sn);
            }

            //更新退单状态
            StoreOrderRefundRepository::edit_one_by_where(['id' => $refund_id], (array)$up_array);

            return hello_success('成功');

        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

    //根据 退单id 处理退单推送消息；
    public function get_push_message($data = [])
    {
        $arr_option['with'] = ['get_order_refund_goods'];
        $arr_option['field'] = ['id', 'user_id', 'shop_id', 'apply_state', 'refund_amount'];

        if (!empty($data['refund_order_id'])) {
            $where = ['id' => $data['refund_order_id']];
        } elseif (!empty($data['refund_no'])) {
            $where = ['refund_no' => $data['refund_no']];
        } else {
            return hello_error('条件错误！');
        }
        $result = StoreOrderRefundRepository::get_one_by_where($where, $arr_option);

        if ($result->first()) {
            $info = $result->toarray();

            $goods = array_shift($info['get_order_refund_goods']);
            $goods_img = $goods['order_goods']['goods_pic']['full_src'];
            $goods_name = '您购买的【' . $goods['order_goods']['goods_name'];

            if (strlen($goods_name) > 40) {
                $goods_name = mb_substr($goods_name, 0, 20) . '...';
            }
            //消息推送
            $message = [
                'img' => $goods_img,              //图片地址  string
                'title' => $data['title'],        //标题  string
                'content' => $goods_name . '】' . $data['content'],    //内容  string
                'user_id' => $info['user_id'],    //用户id   int
                'pid' => 3,                       //消息类型  1：系统消息  2：活动消息  3：订单消息  int
                'order_id' => $info['id'],        //订单id  int
                'j_extend' => ['pid' => 3],       //极光推送的扩展字段  array
                'm_extend' => [                   //消息列表扩展字段    array
                    'is_refund_mes' => 2,         //售后消息
                    'order_type' => 1,
                    'type' => $data['type'],
                    'price' => $info['refund_amount'],
                    'order_status' => $info['apply_state'],
                    'updated_at' => date('Y-m-d H:i:s')
                ]
            ];

            push_message($message);
            return hello_success('成功！');
        }

        return hello_error('订单不存在！');
    }

    /**
     * 导出Excel
     */
    public function get_all_list($arr_search)
    {
        try {
            $where['shop_id'] = $arr_search['shop_id'];//门店id
            if (!empty($arr_search['refund_no'])) {
                $where['refund_no'] = $arr_search['refund_no'];
            }
            if (!empty($arr_search['apply_state'])) {
                $where['apply_state'] = $arr_search['apply_state'];
            }

            $arr_option['where'] = $where;
            $arr_option['with'] = ['get_order_refund_goods', 'refund_reason_id'];

            $data = StoreOrderRefundRepository::get_all($arr_option)->toArray();

            $orderList = [];
            foreach ($data as $key => $value) {
                $state = StoreOrderRefundRepository::apply_state($value['apply_state']);
                $orderList[$state][] = $value;
            }

            return $orderList;
        } catch (\Exception $exception) {
            return hello_error('失败', [], $exception->getMessage());
        }
    }

}